#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Project: spd-sxmcc
"""
@author: lyndon
@time Created on 2018/9/14 10:03
@desc
"""
import json, urllib
from urllib import urlencode


# ----------------------------------
# 问答机器人调用示例代码 － 聚合数据
# 在线接口文档：http://www.juhe.cn/docs/112
# ----------------------------------

def main():
    # 配置您申请的APPKey
    appkey = "*********************"

    # 1.问答
    request1(appkey, "GET")

    # 2.数据类型
    request2(appkey, "GET")


# 问答
def request1(appkey, m="GET"):
    url = "http://op.juhe.cn/robot/index"
    params = {
        "key": appkey,  # 您申请到的本接口专用的APPKEY
        "info": "",  # 要发送给机器人的内容，不要超过30个字符
        "dtype": "",  # 返回的数据的格式，json或xml，默认为json
        "loc": "",  # 地点，如北京中关村
        "lon": "",  # 经度，东经116.234632（小数点后保留6位），需要写为116234632
        "lat": "",  # 纬度，北纬40.234632（小数点后保留6位），需要写为40234632
        "userid": "",  # 1~32位，此userid针对您自己的每一个用户，用于上下文的关联

    }
    params = urlencode(params)
    if m == "GET":
        f = urllib.urlopen("%s?%s" % (url, params))
    else:
        f = urllib.urlopen(url, params)

    content = f.read()
    res = json.loads(content)
    if res:
        error_code = res["error_code"]
        if error_code == 0:
            # 成功请求
            print
            res["result"]
        else:
            print
            "%s:%s" % (res["error_code"], res["reason"])
    else:
        print
        "request api error"


# 数据类型
def request2(appkey, m="GET"):
    url = "http://op.juhe.cn/robot/code"
    params = {
        "dtype": "",  # 返回的数据格式，json或xml，默认json
        "key": appkey,  # 您申请本接口的APPKEY，请在应用详细页查询

    }
    params = urlencode(params)
    if m == "GET":
        f = urllib.urlopen("%s?%s" % (url, params))
    else:
        f = urllib.urlopen(url, params)

    content = f.read()
    res = json.loads(content)
    if res:
        error_code = res["error_code"]
        if error_code == 0:
            # 成功请求
            print
            res["result"]
        else:
            print
            "%s:%s" % (res["error_code"], res["reason"])
    else:
        print
        "request api error"


if __name__ == '__main__':
    main()